package com.kayang.wechat.controller;

import com.kayang.common.CommonException;
import com.kayang.nadapt.util.LogHelper;
import com.kayang.wechat.config.WeChatConfig;
import com.kayang.wechat.service.AccessTokenService;
import com.kayang.wechat.misc.encryption.AesException;
import com.kayang.wechat.misc.encryption.WXBizMsgCrypt;
import com.kayang.wechat.pojo.AppIdentication;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class CallBackController extends BaseController {
    @Autowired
    AccessTokenService tokenService;

    @Autowired
    WeChatConfig weChatConfig;

    @RequestMapping("/callback")
    public ResponseEntity callback(HttpServletRequest request, HttpServletResponse response) {
        String msg = "";
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            msg = get(request, response);
        } else {
            msg = post(request, response);
        }

        return ResponseEntity.ok(msg);
    }


    private String get(HttpServletRequest request, HttpServletResponse response) {
        String ret = "";
        String appkey = request.getParameter("appkey");
        try {
            AppIdentication appIdentication = tokenService.getAppIdentication(appkey);
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(appIdentication.getToken(), appIdentication.getEncodingAESKey(), appIdentication.getCorpId());
            // 解析出url上的参数值如下：
            String sVerifyMsgSig = request.getParameter("msg_signature");
            String sVerifyTimeStamp = request.getParameter("timestamp");
            String sVerifyNonce = request.getParameter("nonce");
            String sVerifyEchoStr = request.getParameter("echostr");
            // 验证URL成功，将sEchoStr返回
            ret = wxcpt.verifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);

        } catch (Exception e) {
            LogHelper.error(e);
            throw new CommonException("回调解密回复消息出现异常");
        }
        return ret;
    }


    private String post(HttpServletRequest request, HttpServletResponse response) {
        String ret = "";
        String appkey = request.getParameter("appkey");
        AppIdentication appIdentication = tokenService.getAppIdentication(appkey);
        // 实际回调事件处理
        // 微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        String msg = "";
        WXBizMsgCrypt wxcpt = null;
        try {
            // 从请求中读取整个post数据
            InputStream inputStream = request.getInputStream();
            // commons.io.jar 方法
            String postData = IOUtils.toString(inputStream, "UTF-8");
            wxcpt = new WXBizMsgCrypt(appIdentication.getToken(), appIdentication.getEncodingAESKey(), appIdentication.getCorpId());
            // 解密消息
            msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);
        } catch (AesException | IOException e) {
            LogHelper.error(e);
            throw new CommonException("解密回复消息出现异常");
        }

        // 调用核心业务类接收消息、处理消息
        String respMessage = ""; // TODO CoreService.processRequest(request, msg);

        try {
            // 加密回复消息
            ret = wxcpt.EncryptMsg(respMessage, timestamp, nonce);
        } catch (AesException e) {
            LogHelper.error(e);
            throw new CommonException("加密回复消息出现异常!");
        }

        return ret;
    }

}
